package com.emep.changzhi.analyse.http.systeminfo;

import com.alibaba.fastjson.JSONObject;
import com.emep.changzhi.analyse.config.RedisClient;
import com.emep.changzhi.analyse.config.SmsConfig;
import com.emep.changzhi.analyse.entity.systeminfo.SysUserInfo;
import com.emep.changzhi.analyse.model.ResultBean;
import com.emep.changzhi.analyse.model.Token;
import com.emep.changzhi.analyse.service.systeminfo.SysUserInfoService;
import com.emep.changzhi.analyse.utils.*;

import io.swagger.annotations.*;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;

import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Wangcc
 * @Description: 用户控制器
 * @date 2018/2/23 13:51
 * @version V1.0
 */
@Slf4j
@RestController
@RequestMapping("user")
@Api(value="用户controller",tags={"用户操作接口"})
public class SysUserInfoController {

    @Autowired
    private SysUserInfoService sysUserInfoService;
    @Autowired
    private SmsConfig smsConfig;

    @Autowired
    private RedisClient redisClient;
    /**
     * 查询所有用户
     * @return
     */
    @ApiOperation(value="获取用户列表", notes="无参数获取所有用户信息")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @GetMapping(value = "list")
    public ResultBean<Collection<SysUserInfo>> queryUser(){
        return new ResultBean<Collection<SysUserInfo>>(sysUserInfoService.findAllUsers());
    }

    /**
     * 新增用户和权限
     * @param payload
     * @return
     */
    @ApiOperation(value="新增用户", notes="新增用户")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
                    @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
                    @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "修改时传的id", required = false, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "userName", value = "登录名", required = true, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "phone", value = "用户手机号", required = true, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "roleId", value = "角色id", required = false, dataType = "String",paramType="query")
    })
    @PostMapping(value = "add")
    public ResultBean<SysUserInfo> addAndRole(@RequestParam Map<String, Object> payload){
        ResultBean result = DataValidator.validateMapData(payload, "userName","phone");
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS){
           return result.boolAdd(sysUserInfoService.saveAndRole(payload)) ;
        }
        return  result;
    }

    /**
     * 通过id 查询用户
     * @param payload
     * @return
     */
    @ApiOperation(value="根据id 查询用户", notes="根据用户的id来获取用户详细信息")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "query")
    @GetMapping(value = "info")
    public ResultBean<SysUserInfo> queryUser( @RequestParam Map<String, Object> payload){
        ResultBean result = DataValidator.validateMapData(payload, "id");
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS) {
             return  result.ok(sysUserInfoService.findId(payload.get("id").toString()));
        }
        return  result;
    }

    /**
     * 根据id 删除用户
     * @param payload
     */
    @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String",paramType = "query")
    @DeleteMapping(value = "delete")
    public  ResultBean<Boolean> delete(@RequestParam Map<String, Object> payload){
        ResultBean result = DataValidator.validateMapData(payload, "id");
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS){
           return result.bool(sysUserInfoService.deleteUser(payload.get("id").toString()));
        }
          return result;
    }

    /**
     * 分页查询用户列表
     * page，第几页，从0开始，默认为第0页
     * size，每一页的大小，默认为20
     * sort，排序相关的信息，以property,property(,ASC|DESC)的方式组织，例如sort=firstname&sort=lastname,desc表示在按firstname正序排列基础上按lastname倒序排列
     * @param
     * @return
     */
    @ApiOperation(value="分页查询用户", notes="分页无参数查询用户")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "pageSize", value = "数量", required = true, dataType = "String",paramType="query"),
    })
    @GetMapping("paging")
    public ResultBean<Page<SysUserInfo>> showUsers(@RequestParam Map<String, Object> payload) {
        ResultBean result = DataValidator.validateMapData(payload, "pageIndex","pageSize");
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS){
            Page<SysUserInfo> pageSysUserInfo = sysUserInfoService.findAll(Integer.parseInt(payload.get("pageIndex")
                    .toString()),Integer.parseInt(payload.get("pageSize").toString()));
             return result.ok(pageSysUserInfo);
        }
        return result;
    }

    /**
     * 分页查询用户列表
     * page，第几页，从0开始，默认为第0页
     * size，每一页的大小，默认为20
     * sort，排序相关的信息，以property,property(,ASC|DESC)的方式组织，例如sort=firstname&sort=lastname,desc表示在按firstname正序排列基础上按lastname倒序排列
     * @param
     * @return
     */
    @ApiOperation(value="分页带参数查询用户", notes="分页带参数查询用户")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "pageSize", value = "数量", required = true, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "areaCode", value = "行政区划", required = false, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = false, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "userName", value = "登录名", required = false, dataType = "String",paramType="query"),
    })
    @GetMapping("paging/query")
    public ResultBean<Page<SysUserInfo>> pageUsers(@RequestParam Map<String, Object> payload) {
        ResultBean result = DataValidator.validateMapData(payload, "pageIndex","pageSize");
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS){
            SysUserInfo sysUserInfo = new SysUserInfo();
            sysUserInfo.setPhone(payload.containsKey("phone") ?payload.get("phone") != null ? payload.get("phone").toString():"":"" );
            sysUserInfo.setUserName(payload.containsKey("userName") ?payload.get("userName") != null ? payload.get("userName").toString():"":"" );
            Page<SysUserInfo> pageSysUserInfo = sysUserInfoService.findBookCriteria(Integer.parseInt(payload.get("pageIndex") .toString()),Integer.parseInt(payload.get("pageSize").toString()),sysUserInfo);
            return result.ok(pageSysUserInfo);
        }
        return result;
    }
    /**
     * 新增用户手机号
     * @param payload
     * @return
     */
    @ApiOperation(value="新增用户手机号", notes="新增用户手机号")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "登录名", required = true, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "phone", value = "用户手机号", required = true, dataType = "String",paramType="query"),
    })
    //@PreAuthorize("hasAnyRole('ROLE_user')")
    @PostMapping(value = "add/phone")
    public ResultBean<SysUserInfo> add(@RequestParam Map<String, Object> payload){
        ResultBean result = DataValidator.validateMapData(payload);
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS){
            return result.boolAdd(sysUserInfoService.saveUser(payload)) ;
        }
        return  result;
    }



    /**
     * 检查手机号是否合法
     * @param payload
     */
    @ApiOperation(value="检查手机号是否合法", notes="根据url的phone检查手机号是否合法")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String",paramType = "query")
    @GetMapping(value = "islegal")
    public  ResultBean<String> islegal(@RequestParam Map<String, Object> payload){
        ResultBean result = DataValidator.validateMapData(payload, "phone");
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS){
            return result.ok(sysUserInfoService.islegal(payload.get("phone").toString()));
        }
        return result;
    }

    /**
     * 用户登录接口
     * @param payload
     */
    @ApiOperation(value="用户登录接口", notes="根据url的phone用户登录接口")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParams({

            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "captcha", value = "验证码", required = true, dataType = "String",paramType="query"),
    })
    @GetMapping(value = "login")
    public  ResultBean<String> login(@RequestParam Map<String, Object> payload,HttpSession session){

        ResultBean result = DataValidator.validateMapData(payload, "phone","captcha");
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS){
            String reslet =  sysUserInfoService.login(payload.get("phone").toString(),payload.get("captcha").toString(),session);
            if(!StringUtils.isEmpty(reslet)){
                    Token token =   new Token();
                    token.setToken(reslet);
                    return result.ok(token);
            }else {
                return result.error("登录失败");
            }
        }
        return result;
    }

    /**
     * 获取手机验证码
     * @author xieyang
     * @param payload
     * @return
     */

    @ApiOperation(value="发送验证码", notes="发送验证码")
    @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String",paramType="query")
    @CrossOrigin
    @PostMapping(value = "captcha")
    public ResultBean<String> getSms(@RequestParam Map<String, Object> payload) {
        ResultBean result = DataValidator.validateMapData(payload,"phone");
        if(result.getCode() == Constant.RESULT_CODE_SUCCESS){
            Integer randomNum = (int) ((Math.random() * 9 + 1) * 1000);//生产随机数据
            String log1 = new SmsUtil().SubmitSms(smsConfig.username, smsConfig.password, payload.get("phone").toString(),
                            "此为测试模板" + randomNum + "。有效时间15分钟。【智网】", smsConfig.productNum);
            Pattern pattern = Pattern.compile("[0-9]*");
            Matcher isNum = pattern.matcher(log1);
            //验证是否发送成功
            if (isNum.matches() && log1.length() == 18) {
                //成功后存入redis
                redisClient.setWithExpireTime(payload.get("phone").toString(), String.valueOf(randomNum), 900);
                log.info("发送验证码：" + randomNum);
//            session.setAttribute(payload.get("phone").toString(), randomNum.toString());//存入session
//            session.setMaxInactiveInterval(7200);
                return result.ok(randomNum);
            }else {
                return result.error("验证码发送失败!");
            }
        }
        return result;
    }



    /**
     * 根据用户token获取用户信息
     * @param payload
     * @return
     */
    @ApiOperation(value="根据用户token获取用户信息", notes="根据用户token获取用户信息")
    @ApiResponses({ @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败，服务器内部异常"),
            @ApiResponse(code = 303, message = "权限不足") })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", required = true, dataType = "String",paramType="query"),

    })
    @GetMapping(value = "token")
    public ResultBean<SysUserInfo> findUserByToken(@RequestParam Map<String, Object> payload,HttpSession session){
        ResultBean result = DataValidator.validateMapData(payload,"token");
        if (result.getCode() == Constant.RESULT_CODE_SUCCESS){
            SysUserInfo sysUserInfo=sysUserInfoService.findUserByToken(payload.get("token").toString(),session);
            System.out.println(sysUserInfo);
            return result.ok(sysUserInfo) ;
        }
        return result;
    }

    }



